<template>
  <div id="app">
    <el-select filterable :filter-method="pinyinMatch" v-model="value1" :disabled="role >=  3" placeholder="请选择学院" >
      <el-option
        v-for="item in source"
        :key="item"
        :label="item"
        :value="item">
      </el-option>
    </el-select>

    <el-select v-model="value2" placeholder="请选择年级">
      <el-option
        v-for="item in secondList"
        :key="item"
        :label="item"
        :value="item">
      </el-option>
    </el-select>

   <el-select v-model="value3" placeholder="请选择班级">
      <el-option
        v-for="item in thirdList"
        :key="item"
        :label="item"
        :value="item">
      </el-option>
    </el-select>
    &nbsp;
    <div class="block" style="width: 220px; margin: 0; padding: 0;">
      <el-date-picker
        v-model="start"
        type="datetime"
        placeholder="选择开始日期时间"
        align="right"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions">
      </el-date-picker>
    </div>
    <div class="block" style="width: 220px;  margin: 0; padding: 0;">
      <el-date-picker
        v-model="end"
        type="datetime"
        placeholder="选择结束日期时间"
        align="right"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions">
      </el-date-picker>
    </div>
    &nbsp;
    <el-button type="primary" @click="reset()" size="small">重置</el-button>
    <!-- <el-button type="average" @click="sum()" size="small">总分</el-button> -->
    <el-button type="average" @click="sum()" size="small" v-show="title === '平均分'">总分</el-button>
    <el-button type="average" @click="avg()" size="small" v-show="title === '总分'">平均分</el-button>
    <!-- <el-button type="average" @click="toGo('/echar/reasonCompare')" size="small">对比</el-button> -->
    <br />
    <br />
    <div id="main" style="width: 100%;height:600px;margin: 0 auto;"></div>
  </div>
</template>
<script>
import pinyin from 'pinyin-match'
import { debounce } from '@/myUtils/debounce'
export default {
  name: 'app',
  data () {
    return {
      title: '平均分',
      MapData: [],
      levelFirst: '',
      firstList: [],
      levelSecond: '',
      secondList: [],
      levelThird: '',
      thirdList: [],
      levelFourth: '',
      role: 0,
      defaultCollege: '', // 默认学院名称
      fourthList: [],
      copyDept: '',
      source: '',
      dataList: [], // 整个树表
      erDataList: [], // 存二级表
      sanDataList: [], // 存三级表
      options: [{
        value: '大庆师范学院',
        label: '大庆师范学院'
      }],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      temp: {
        value: '',
        label: ''
      },
      value1: '', // 学院
      value2: '', // 年级
      value3: '', // 班级
      v2length: 0,
      start: '',
      end: '',
      timeout: '',
      nameX: [], // 存入机构名称
      valueY: [], // 存入机构的总分或者平均分
      valueSUM: [], // 存入机构的总分
      valueAVG: [], // 存入的平均分
      params: {
        institute: '',
        grade: '',
        classe: '',
        startDate: '', // 开始时间
        endDate: '' // 结束时间
      },
      data: {
        ids: '',
        flag: ''
      }
    }
  },
  // 当检测到value1变的时候，查询原本的dataList通过对应的位置,
  // 然后获取secondList中的值,依次类推，当监听到上一级变化的时候，后面的数据变为空
  watch: {
    value1 (newname, oldname) {
      // 进行重置
      this.secondList = []
      this.value2 = ''
      this.thirdList = []
      this.value3 = ''
      this.re()
      if (newname === ' ') {
        newname = ''
        this.params.institute = ''
        this.getMap()
        return
      }
      for (let k = 0; k < this.dataList.length; k++) {
        if (this.dataList[k].name === newname) { // 检测选择了哪个
          // 构建参数
          this.data.ids = this.dataList[k].parentIds + this.dataList[k].id + ','
          this.params.institute = newname
          this.getMapave()
          // 更改选择框
          this.erDataList = this.dataList[k].children
          this.secondList.push(' ')
          for (let i = 0; i < this.erDataList.length; i++) {
            this.secondList.push(this.erDataList[i].name)
          }
          return
        }
      }
    },
    value2 (newname, oldname) {
      this.v2length = this.value2.length
      this.data.flag = ''
      this.thirdList = []
      this.value3 = ''
      this.re()
      if (newname === ' ') {
        newname = ''
        this.params.grade = ''
        this.getMap()
        return
      }
      if (newname === '') {
        return
      }
      for (let w = 0; w < this.dataList.length; w++) {
        if (this.erDataList[w].name === newname) {
          // 构建参数
          this.data.ids = this.erDataList[w].parentIds + this.erDataList[w].id + ','
          this.params.grade = newname
          this.getMapave()
          // 更改选择框
          this.sanDataList = this.erDataList[w].children
          this.thirdList.push(' ')
          for (let a = 0; a < this.sanDataList.length; a++) {
            this.thirdList.push(this.sanDataList[a].name)
          }
          return
        }
      }
    },
    value3 (newname, oldname) {
      this.re()
      if (newname === ' ') {
        newname = ''
      }
      this.params.classe = newname
      this.getMapave()
    },
    start (newname, oldname) {
      this.params.startDate = newname
      if (newname === '') {
        return
      }
      this.re()
      this.getMapave()
    },
    end (newname, oldname) {
      this.params.endDate = newname
      if (newname === '') {
        return
      }
      this.re()
      this.getMapave()
    }
  },
  mounted () {
    this.getTree()
  },
  methods: {
    // 获取当前登录用户信息
    getUserInfo () {
      this.$http({
        url: '/sys/user/info',
        method: 'get'
      }).then(({data}) => {
        if (data.success) {
          // 学院账号
          if (data.user.roleIds === '52211ea85fbe423a8f3d11c39e09dc51') {
            this.role = 2
            this.officeName = data.user.office.name
            this.defaultCollege = this.officeName
          }
          if (data.user.roleIds === '2a21eb97b6dc4b1ba64ca654d38be348') {
            // 辅导员老师账号
            this.role = 3
            this.officeName = data.user.office.name
            this.defaultCollege = this.officeName
            for (let k = 0; k < this.dataList.length; k++) {
              if (this.dataList[k].name === this.officeName) { // 检测选择了哪个
                // 构建参数
                this.data.ids = this.dataList[k].parentIds + this.dataList[k].id + ','
                // 更改选择框
                this.erDataList = this.dataList[k].children
                for (let i = 0; i < this.erDataList.length; i++) {
                  this.secondList.push(this.erDataList[i].name)
                }
              }
            }
          }
          if (data.user.roleIds === 'b930ac75924c47f99ac92c6fc8c3accb') {
            // 学生账号
            this.role = 4
            this.searchForm.name = data.user.name
          }
          this.value1 = this.defaultCollege
          this.initMethods()
        }
      })
    },
    initMethods () {
      this.source = this.firstList
      this.$http({
        url: '/graph/Graph/byReason',
        method: 'post',
        params: {
          institute: this.defaultCollege,
          grade: '',
          classe: '',
          startDate: '',
          endDate: ''
        }
      }).then(({data}) => {
        this.MapData = data.list
        this.re() // 重置数据
        for (let i = 0; i < this.MapData.length; i++) {
          let tempAVG = this.MapData[i].value / this.MapData[i].average  // 计算平均分
          this.MapData[i].value = tempAVG  // 放到MapData中
        }
        for (let i = 0; i < this.MapData.length - 1; i++) {  // 选择排序
          for (let j = i + 1; j < this.MapData.length; j++) {
            if (this.MapData[i].value < this.MapData[j].value) {
              let temp = this.MapData[i].value
              let reasontemp = this.MapData[i].addReason  // 让x轴的数据跟随y轴数据变化
              this.MapData[i].value = this.MapData[j].value
              this.MapData[i].addReason = this.MapData[j].addReason
              this.MapData[j].value = temp
              this.MapData[j].addReason = reasontemp
            }
          }
        }
        this.sortAssign()
        this.drawChart()
      })
    },
    // 注：Dept下拉框绑定的数组对象，copyDept是初始化copy的Dept
    pinyinMatch (val) {
      this.copyDept = this.firstList
      if (val) {
        let result = [] // 声明一个空数组保存搜索内容
        this.copyDept.forEach(e => { // 循环判断内容和拼音首字母是否匹配
          let m = pinyin.match(e, val)
          if (m) {
            result.push(e)
          }
        })
        this.source = result // 返回匹配的数组
      } else {
        this.source = this.copyDept // 未输入返回开始copy的原数组
      }
    },
    sum () {
      this.title = '总分'
      this.re()
      this.valueY = this.valueSUM
      this.getMapsum()
    },
    avg () {
      this.title = '平均分'
      this.re()
      this.valueY = this.valueAVG
      this.getMapave()
    },
    toGo (path) {
      this.$router.push(path)
    },
    deposit () {
      for (let i = 0; i < this.MapData.length; i++) {
        if (this.MapData[i].value !== 0) {
          this.nameX.push(this.MapData[i].addReason)
          this.valueSUM.push(this.MapData[i].value)
          this.valueAVG.push(this.MapData[i].average)
          this.valueY.push(this.MapData[i].average)
        }
      }
    },
    // 平均分排序的赋值
    sortAssign () {
      for (let i = 0; i < this.MapData.length; i++) {
        if (this.MapData[i].value !== 0) {
          this.nameX.push(this.MapData[i].addReason)
          this.valueSUM.push(this.MapData[i].value)
          this.valueY.push(this.MapData[i].value)
        }
      }
    },
    re () {
      this.nameX = []
      this.valueY = []
    },
    reset () {
      this.re()
      this.value1 = ''
      this.value2 = ''
      this.params.classe = ''
      this.params.institute = ''
      this.params.grade = ''
      this.params.endDate = ''
      this.params.startDate = ''
      this.start = ''
      this.end = ''
      debounce(this.getMapave, 2000, null, this)()
    },
    getMap () {
      this.$http({
        url: '/graph/Graph/byReason',
        method: 'post',
        params: this.params
      }).then(({data}) => {
        this.MapData = data.list
        this.deposit()
        this.drawChart()
      })
    },
    // 总分降序排列
    getMapsum () {
      this.$http({
        url: '/graph/Graph/byReason',
        method: 'post',
        params: this.params
      }).then(({data}) => {
        this.MapData = data.list
        this.re()
        for (let i = 0; i < this.MapData.length - 1; i++) {  // 选择排序
          let max = i
          for (let j = i + 1; j < this.MapData.length; j++) {
            if (this.MapData[max].value < this.MapData[j].value) {
              max = j
            }
          }
          if (max !== i) {
            let temp = this.MapData[i].value
            let sortTemp = this.MapData[i].addReason // 让x轴的数据跟随y轴数据变化
            this.MapData[i].value = this.MapData[max].value
            this.MapData[i].addReason = this.MapData[max].addReason
            this.MapData[max].value = temp
            this.MapData[max].addReason = sortTemp
          }
        }
        this.sortAssign()
        this.drawChart()
      })
    },
    // 平均分降序排列
    getMapave () {
      this.$http({
        url: '/graph/Graph/byReason',
        method: 'post',
        params: this.params
      }).then(({data}) => {
        this.MapData = data.list
        // console.log(data)
        this.re() // 重置数据
        for (let i = 0; i < this.MapData.length; i++) { // 计算平均分
          let tempAVG = this.MapData[i].value / this.MapData[i].average
          this.MapData[i].value = tempAVG
        }
        for (let i = 0; i < this.MapData.length - 1; i++) {  // 选择排序
          for (let j = i + 1; j < this.MapData.length; j++) {
            if (this.MapData[i].value < this.MapData[j].value) {
              let temp = this.MapData[i].value
              let reasontemp = this.MapData[i].addReason  // 让x轴的数据跟随y轴数据变化
              this.MapData[i].value = this.MapData[j].value
              this.MapData[i].addReason = this.MapData[j].addReason
              this.MapData[j].value = temp
              this.MapData[j].addReason = reasontemp
            }
          }
        }
        this.sortAssign()
        this.drawChart()
      })
    },
    getTree () {
      this.$http({
        url: '/sys/office/treeData',
        method: 'get'
      }).then(({data}) => {
        // 把整个子节点都存到树表中
        this.dataList = data.treeData[0].children
        this.getNext()
        this.getUserInfo()
      })
    },
    getNext () {
      this.firstList.push(' ')
      for (let i = 0; i < this.dataList.length; i++) {
        this.firstList.push(this.dataList[i].name)
      }
    },
    drawChart () {
      var chartDom = document.getElementById('main')
      var myChart = this.$echarts.init(chartDom)
      var option
      option = {
        title: {
          text: this.value1 + this.value2 + this.value3 + this.title + '得分情况图表',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.nameX,
          axisLabel: {
            interval: 0,
            formatter: function (params) {
              var newParamsName = ''
              const paramsNameNumber = params.length
              const provideNumber = 6 // 单行显示文字个数
              const rowNumber = Math.ceil(paramsNameNumber / provideNumber)
              if (paramsNameNumber > provideNumber) {
                for (let p = 0; p < rowNumber; p++) {
                  var tempStr = ''
                  var start = p * provideNumber
                  var end = start + provideNumber
                  if (p === rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber)
                  } else {
                    tempStr = params.substring(start, end) + '\n'
                  }
                  newParamsName += tempStr
                }
              } else {
                newParamsName = params
              }
              return newParamsName
            }
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.valueY,
            name: 'Direct',
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              normal: {
                color: function (params) {
                  let colorList = [
                    '#46a4f7', '#36cbcb', '#11D074', '#fad337', '#9b5de5', '#f97476', '#655b7c', '#ffa62b', '#ffb8ff', '#80eb9a', '#feebad', '#c49f86', '#4aa0b6', '#babd8e'
                  ]
                  return colorList[params.dataIndex]
                }
              }
            }
          }
        ]
      }

      option && myChart.setOption(option)
    }
  }

}
</script>
